package com.example.mapping.manage;

import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.example.mapping.common.exception.MappingBizException;
import com.example.mapping.constant.Constants;
import com.example.mapping.convert.RuleConvert;
import com.example.mapping.domain.Rule;
import com.example.mapping.dto.RuleDto;
import com.example.mapping.dto.RuleQueryDto;
import com.example.mapping.sevice.RuleService;
import com.example.mapping.vo.RuleVo;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Objects;

import static com.example.mapping.common.exception.MappingErrorCodeEnum.*;

/**
 * 校验规则manage类
 *
 * @author baoyoujia
 */
@Component
public class RuleManage {

    private final RuleService ruleService;

    private final RuleConvert ruleConvert;

    public RuleManage(RuleService ruleService, RuleConvert ruleConvert) {
        this.ruleService = ruleService;
        this.ruleConvert = ruleConvert;
    }

    public PageDTO<RuleVo> getRuleByPage(RuleQueryDto ruleQueryDto) {
        PageDTO<Rule> pageDTO = new PageDTO<>();
        pageDTO.setCurrent(ruleQueryDto.getCurrent());
        pageDTO.setSize(ruleQueryDto.getSize());
        PageDTO<Rule> rulePage = ruleService.page(pageDTO);
        if (CollectionUtils.isEmpty(rulePage.getRecords())) {
            return new PageDTO<>();
        }
        return ruleConvert.modelPage2Vo(rulePage);
    }

    public RuleVo getRule(Long id) {
        Rule rule = ruleService.getById(id);
        if (Objects.isNull(rule)) {
            return new RuleVo();
        }
        return ruleConvert.model2Vo(rule);
    }

    public Boolean addRule(RuleDto ruleDto) {
        Rule rule = ruleConvert.dto2Model(ruleDto);
        boolean result = ruleService.save(rule);
        if (!result) {
            throw new MappingBizException(ADD_RULE_ERROR);
        }
        return true;
    }

    public Boolean editRule(RuleDto ruleDto) {
        Rule rule = ruleConvert.dto2Model(ruleDto);
        boolean result = ruleService.updateById(rule);
        if (!result) {
            throw new MappingBizException(EDIT_RULE_ERROR);
        }
        return true;
    }

    public Boolean delRule(Long id) {
        Rule rule = ruleService.getById(id);
        rule.setSysDelete(Constants.Number.INT_2);
        boolean result = ruleService.updateById(rule);
        if (!result) {
            throw new MappingBizException(DEL_RULE_ERROR);
        }
        return true;
    }
}
